const BaseController = require('./base_controller.js');
const cloudBase = require('../framework/cloud/cloud_base.js');
const timeUtil = require('../framework/helpers/time_util.js');
const dataUtil = require('../framework/helpers/data_util.js');
const dbUtil = require('../framework/database/db_util.js');
const setupUtil = require('../framework/helpers/setup/setup_util.js');

class HomeController extends BaseController {

    async getSetup() {
        try {
            // 校验参数
            let rules = {
                key: 'must|string|name=KEY'
            };
            
            // 取得数据
            let input = this.validateData(rules);
            
            // 获取设置
            let content = await setupUtil.get(input.key);
            return this.getTrueReturnData(content);
        } catch (err) {
            console.error('获取设置失败:', err);
            return this.getFalseReturnData('获取设置失败');
        }
    }

    async workData() {
        // 获取用户ID
        let userId = this._userId;
        if (!userId) return this.getFalseReturnData('用户未登录');

        try {
            // 获取待办事项数量
            let todoCount = await dbUtil.count('flow_main', {
                FLOW_STATUS: dbUtil.getCmd().in([0, 1]), // 待处理的状态
                USER_ID: userId
            });

            // 获取已办事项数量
            let doneCount = await dbUtil.count('flow_main', {
                FLOW_STATUS: dbUtil.getCmd().in([2, 3]), // 已完成的状态
                USER_ID: userId
            });

            // 获取进行中的项目数量
            let projectCount = await dbUtil.count('project_main', {
                STATUS: 1, // 进行中状态
                USER_ID: userId
            });

            // 获取待完成任务数量
            let taskCount = await dbUtil.count('task_main', {
                STATUS: 0, // 未完成状态
                USER_ID: userId
            });

            return this.getTrueReturnData({
                todoCount,
                doneCount,
                projectCount,
                taskCount
            });

        } catch (err) {
            console.error('获取工作数据失败:', err);
            return this.getFalseReturnData('获取工作数据失败');
        }
    }

    async dynamicList() {
        // 获取用户ID
        let userId = this._userId;
        if (!userId) return this.getFalseReturnData('用户未登录');

        try {
            // 获取最近的动态信息
            let list = await dbUtil.getList('dynamic_main', {
                USER_ID: userId
            }, '*', {
                ADD_TIME: 'desc'
            }, 1, 10);

            if (!list || !Array.isArray(list.list)) {
                return this.getTrueReturnData([]);
            }

            // 处理每条动态的数据
            list = list.list.map(item => ({
                _id: item._id,
                avatar: item.AVATAR || '/projects/oa/images/icon/empty.png',
                name: item.NAME,
                time: timeUtil.timestamp2Time(item.ADD_TIME),
                content: item.CONTENT,
                type: item.TYPE,
                typeText: this._getTypeText(item.TYPE)
            }));

            return this.getTrueReturnData(list);

        } catch (err) {
            console.error('获取动态列表失败:', err);
            return this.getFalseReturnData('获取动态列表失败');
        }
    }

    async statistics() {
        // 获取用户ID
        let userId = this._userId;
        if (!userId) return this.getFalseReturnData('用户未登录');

        try {
            // 获取项目进度
            let projectProgress = await this._getProjectProgress(userId);

            // 获取任务完成率
            let taskCompletion = await this._getTaskCompletion(userId);

            // 获取审批效率
            let approvalEfficiency = await this._getApprovalEfficiency(userId);

            // 获取团队绩效
            let teamPerformance = await this._getTeamPerformance(userId);

            return this.getTrueReturnData({
                projectProgress,
                taskCompletion,
                approvalEfficiency,
                teamPerformance
            });

        } catch (err) {
            console.error(err);
            return this.getFalseReturnData('获取统计数据失败');
        }
    }

    // 获取公司内部通讯录
    async contactList() {
        // 获取用户ID
        let userId = this._userId;
        if (!userId) return this.getFalseReturnData('用户未登录');

        try {
            // 获取员工列表，按部门分组
            let list = await dbUtil.getAll('user_main', {
                USER_STATUS: 1 // 正常状态的用户
            }, '*', {
                USER_DEPT: 'asc',
                USER_NAME: 'asc'
            });

            if (!list || !Array.isArray(list)) {
                console.error('未能获取用户列表或返回格式错误');
                return this.getTrueReturnData([]);
            }

            // 处理数据：按部门分组
            let result = [];
            let deptMap = {};

            // 先按部门分组
            list.forEach(user => {
                const dept = user.USER_DEPT || '未分配';
                if (!deptMap[dept]) {
                    deptMap[dept] = {
                        dept: dept,
                        users: []
                    };
                }
                
                deptMap[dept].users.push({
                    id: user._id,
                    name: user.USER_NAME,
                    avatar: user.USER_PIC || '/projects/oa/images/icon/empty.png',
                    mobile: user.USER_MOBILE || '',
                    email: user.USER_EMAIL || '',
                    position: user.USER_POSITION || '',
                    dept: user.USER_DEPT || '未分配'
                });
            });

            // 转换为数组
            for (let key in deptMap) {
                result.push(deptMap[key]);
            }

            return this.getTrueReturnData(result);

        } catch (err) {
            console.error('获取通讯录失败:', err);
            return this.getFalseReturnData('获取通讯录失败');
        }
    }

    // 获取项目进度
    async _getProjectProgress(userId) {
        let allProjects = await dbUtil.count('project_main', {
            USER_ID: userId
        });
        let completedProjects = await dbUtil.count('project_main', {
            USER_ID: userId,
            STATUS: 2 // 已完成状态
        });
        return allProjects ? Math.round((completedProjects / allProjects) * 100) : 0;
    }

    // 获取任务完成率
    async _getTaskCompletion(userId) {
        let allTasks = await dbUtil.count('task_main', {
            USER_ID: userId
        });
        let completedTasks = await dbUtil.count('task_main', {
            USER_ID: userId,
            STATUS: 1 // 已完成状态
        });
        return allTasks ? Math.round((completedTasks / allTasks) * 100) : 0;
    }

    // 获取审批效率
    async _getApprovalEfficiency(userId) {
        let now = dataUtil.time();
        let lastWeek = now - 7 * 24 * 60 * 60;
        
        let approvals = await dbUtil.getAll('flow_main', {
            USER_ID: userId,
            ADD_TIME: dbUtil.getCmd().gte(lastWeek)
        });

        if (!approvals.length) return 0;

        let totalTime = 0;
        let count = 0;

        approvals.forEach(approval => {
            if (approval.END_TIME) {
                totalTime += (approval.END_TIME - approval.ADD_TIME);
                count++;
            }
        });

        // 计算平均审批时间（小时），转换为效率百分比
        let avgHours = count ? (totalTime / count) / 3600 : 0;
        // 假设24小时为基准，少于24小时效率为100%，大于24小时按比例递减
        return Math.min(100, Math.round((24 / (avgHours || 24)) * 100));
    }

    // 获取团队绩效
    async _getTeamPerformance(userId) {
        // 这里可以根据实际需求计算团队绩效
        // 示例：根据任务完成率、项目进度等综合计算
        let taskCompletion = await this._getTaskCompletion(userId);
        let projectProgress = await this._getProjectProgress(userId);
        let approvalEfficiency = await this._getApprovalEfficiency(userId);

        return Math.round((taskCompletion + projectProgress + approvalEfficiency) / 3);
    }

    // 获取动态类型文本
    _getTypeText(type) {
        const typeMap = {
            'project': '项目',
            'task': '任务',
            'approval': '审批'
        };
        return typeMap[type] || '';
    }
}

module.exports = HomeController; 